<template>
  <div class="disabled-warp" style="height: calc(100vh - 104px); padding: 20px;">
    <div class="dashboard-container" style=" padding: 20px 25px 10px; ">
      <div
          style="  line-height: 16px; flex-wrap: wrap;   align-items: center;
          font-size: 16px; font-family: Source Han Sans CN;font-weight: bold;color: #2F3745; ">
        <div class="dashboard-inner">
          打印模板
          <el-tooltip class="item" effect="dark" content="温馨提示：表格对应列可以通过拖动改变表格宽度" placement="top">
            <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
          </el-tooltip>
        </div>
      </div>
    </div>

    <div style="  height: calc(100% - 30px); background: #fff;" class="settement-right-content " >
      <div style="width: calc(100% - 50px); margin-left: 25px; margin-right: 25px;">
        <common-operation-form  :list="list"/>

        <el-table style="margin-top: 15px;" @select="changeevent" :height="windowHeight - 10"
                  v-loading="table.loading" :data="table.data" border >
          <el-table-column
              v-for="(item, index) in table.header1"
              :prop="item.prop"
              :index="index" :align="`center`"
              :width="item.width || 'auto'" :header-align="`center`"
              :label="item.label">
            <template slot-scope="scope">
              <span v-if="item.prop === 'defaultType'" style=" ">
                {{ scope.row[item.prop] ? '是' : '否' }}
              </span>
              <span v-else style=" ">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>

          <el-table-column
              label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <template slot-scope="scope">
                <div style="display: flex;">
                  <el-tooltip content="编辑" slot="reference" placement="top">
                    <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="edit(scope.row)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" slot="reference" placement="top">
                    <el-button size="mini" @click="del(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
                  </el-tooltip>
                </div>
              </template>

              <div style="display: flex;">
                <el-tooltip content="编辑模板" slot="reference" placement="top">
                  <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="edit(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="!scope.row['defaultType']" content="设为默认" slot="reference" placement="top">
                  <el-button size="mini" type="success" circle @click="setDefaultTemplate(scope.row)">
                    <svg-icon icon-class="set-default" />
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" slot="reference" placement="top">
                  <el-button size="mini" @click="del(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>


        <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                       :current-page="page.pageNumber"
                       layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               title="编辑" :modal="false"
               width="520px" v-dialog-drag
               custom-class="dialoginte102"
               :visible.sync="editDialog">
      <div>
        <common-dialog-form v-if="editDialog" ref="commondialogformref" :col="dialog.col" :list="dialog.form"/>
      </div>

      <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancel">关闭</el-button>
          <el-button type="primary" size="small"
                      element-loading-spinner="el-icon-loading"
                     :loading="printDialog.creatingLoading" @click="printDialogStatus(true)">{{buttonName}}</el-button>
      </span>
    </el-dialog>

    <el-dialog style="margin-top: 10px;" custom-class="no-header-dialog"
               :fullscreen="true"
               :close-on-click-modal="false"
               width="95%" v-dialog-drag append-to-body
               title="编辑" :show-close="false"
               :visible.sync="printDialog.printDialogVisible">
      <span slot="title"></span>
      <print @printDialogStatus="printDialogStatus" v-if="printDialog.printDialogVisible" :templateData="printDialog.templateData"/>
    </el-dialog>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import {getUserInfo} from "@/utils/auth";
import {createTemplate, delTemplate, setDefaultTemplate} from "@/api/template";
import { addEmployee, deleteEmployeeByEmployeeID} from "@/api/employee";
import Print from "@/components/PurchaseIncoming/print.vue";
import {getTemplateList} from "@/api/template";
import {deepClone, panelList, switchPanel} from "@/utils";

export default {
  name: 'employee_settings',
  components: {CommonOperationForm, CommonDialogForm, Print},
  data() {
    return {
      list: [
        {
          type: 'input',
          text: '模板名称：',
          width: '75px',
          value: '',
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.pageNumber = 1;
            this.getTemplateList();
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-folder-add',
          buttonText: '增加',
          event: () => {
            this.editDialog = true;
            this.buttonName = '立即新增';
            this.dialog.chooseItem = null;
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-printer',
          buttonText: '打印',
          event: () => {

          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-document-add',
          buttonText: '导入',
          event: () => {

          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-takeaway-box',
          buttonText: '导出',
          event: () => {

          }
        },
      ],
      editDialog: false,
      buttonName: '立即新增',
      table: {
        data: [],
        loading: false,
        header1: [
          {"label": "模板名称", "prop": "templateName", width: '250px',},
          {"label": "业务类型", "prop": "businessType"},
          {"label": "纸张", "prop": "paperLabel"},
          {"label": "纸张宽(mm)", "prop": "paperWidth"},
          {"label": "纸张高(mm)", "prop": "paperHeight"},
          {"label": "默认", "prop": "defaultType"},
        ],

      },
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      },
      dialog: {
        col: 1,
        form: [
          [
            {
              text: '业务类型：',
              required: true,
              field: 'businessType',
              width: '90px',
              requiredMessage: "请输入账户名称",
              type: 'businessType',
              value: 0,
              clickEvent: (v) => {
                console.log(v);
                this.dialog.form[0][0].value = v;
              },
              options: [
                // {
                //   "name": "销售预定"
                // },
                {
                  "name": "销售"
                },
                {
                  "name": "销售退货"
                },
                // {
                //   "name": "零售"
                // },
                // {
                //   "name": "零售退货"
                // },
                // {
                //   "name": "积分兑换"
                // },
                // {
                //   "name": "进货预定"
                // },
                {
                  "name": "进货"
                },
                {
                  "name": "进货退货"
                },
                {
                  "name": "库存调拨"
                },
                {
                  "name": "库存盘点"
                },
                // {
                //   "name": "组装拆卸"
                // },
                {
                  "name": "其他入库"
                },
                {
                  "name": "其他出库"
                },
                {
                  "name": "收款"
                },
                {
                  "name": "付款"
                },
                // {
                //   "name": "资金调拨"
                // },
                // {
                //   "name": "标签"
                // },
                // {
                //   "name": "对账单"
                // }
              ],
            },
          ],
          [
            {
              text: '设为默认模板',
              value: true,
              width: '90px',
              rowWidth: '100%',
              field: 'defaultType',
              type: 'checkbox',
            },
          ],
        ],
        copyForm: [
          [
            {
              text: '业务类型：',
              required: true,
              field: 'businessType',
              width: '90px',
              requiredMessage: "请输入账户名称",
              type: 'businessType',
              value: 0,
              clickEvent: (v) => {
                console.log(v);
                this.dialog.form[0][0].value = v;
              },
              options: [
                {
                  "name": "销售预定"
                },
                {
                  "name": "销售"
                },
                {
                  "name": "销售退货"
                },
                {
                  "name": "零售"
                },
                {
                  "name": "零售退货"
                },
                {
                  "name": "积分兑换"
                },
                {
                  "name": "进货预定"
                },
                {
                  "name": "进货"
                },
                {
                  "name": "进货退货"
                },
                {
                  "name": "库存调拨"
                },
                {
                  "name": "库存盘点"
                },
                {
                  "name": "组装拆卸"
                },
                {
                  "name": "其他入库"
                },
                {
                  "name": "其他出库"
                },
                {
                  "name": "收款"
                },
                {
                  "name": "付款"
                },
                {
                  "name": "资金调拨"
                },
                {
                  "name": "标签"
                },
                {
                  "name": "对账单"
                }
              ],
            },
          ],
          [
            {
              text: '设为默认模板',
              value: true,
              width: '90px',
              rowWidth: '100%',
              field: 'defaultType',
              type: 'checkbox',
            },
          ],
        ],
        chooseItem: null,
      },
      printDialog: {
        printDialogVisible: false,
        creatingLoading: false,
        templateData: {
          templateTypeName: '',
          templateID: '',
          paper: {},
          template: {},
        },
        list: [
          {
            text: '选择模板：',
            required: true,
            selectWidth: '280px',
            width: '80px',
            field: 'documentType',
            type: 'selectAllowCreate',
            allowCreate: false,
            options: [],
            value: '',
            changeEvent: (v) => {
              console.log(v);
            }
          },
          {
            value: '',
            width: '85px',
            rowWidth: '100%',
            field: 'defaultSupplier',
            type: 'addButton',
            clickEvent: (v) => {
              if (v === 'add') {

              } else {

              }
            }
          },
        ],
      },
    }
  },
  mounted() {
    this.getTemplateList();
  },
  methods: {
    printDialogStatus(v, changePaper = false, template = "", paper) {
      if (changePaper === true) {
        this.printDialog.templateData['template'] = template;
        this.printDialog.templateData['paper'] = paper;
        return;
      }

      if (v && this.buttonName === '立即新增') {
        this.printDialog.creatingLoading = true;
        createTemplate({
          userID: getUserInfo().userID,
          businessType: this.dialog.form[0][0].options[this.dialog.form[0][0].value].name,
          defaultType: this.dialog.form[1][0].value,
        }).then(res => {
          console.log(res);
          this.printDialog.creatingLoading = false;

          this.printDialog.templateData['template'] = switchPanel(this.dialog.form[0][0].options[this.dialog.form[0][0].value].name, '二等分');
          this.printDialog.templateData['templateID'] = res.data.data._id;
          this.printDialog.templateData['templateName'] = '';
          this.printDialog.templateData['paper'] = {
            "label": "二等分",
            "value": "241 * 140mm",
            "attr": {
              "width": "210",
              "height": "140"
            }
          };
          this.printDialog.templateData['scale'] = 1;
          this.printDialog.templateData['templateTypeName'] = this.dialog.form[0][0].options[this.dialog.form[0][0].value].name;
          this.printDialog.printDialogVisible = v;
        });
      } else if(v && this.buttonName === '立即编辑') {
        this.printDialog.templateData['templateID'] = this.dialog.chooseItem._id;
        this.printDialog.templateData['templateName'] = this.dialog.chooseItem.templateName;
        this.printDialog.templateData['template'] = this.dialog.chooseItem.template;
        this.printDialog.templateData['paper'] = this.dialog.chooseItem.paper;
        this.printDialog.templateData['scale'] = this.dialog.chooseItem.scale;
        this.printDialog.templateData['templateTypeName'] = this.dialog.form[0][0].options[this.dialog.form[0][0].value].name;
        this.printDialog.printDialogVisible = v;
      } else {
        this.printDialog.printDialogVisible = v;
        this.cancel();
        this.getTemplateList();
      }
    },
    getTemplateList() {
      if (this.table.loading)
        return;
      this.table.loading = true;
      getTemplateList({
        userID: getUserInfo().userID,
        templateName: this.list[0].value,
        pageSize: this.page.pageSize,
        pageNumber: this.page.pageNumber,
      }).then(res => {
        console.log(res);
        this.table.data = res.data.data;
        this.page.total = res.data.page.totalDocuments;
        this.table.loading = false;
      });
    },
    changeevent(selection, row) {
      console.log(selection, row);
    },
    setDefaultTemplate(item) {
      setDefaultTemplate({
        _id: item._id,
        userID: getUserInfo().userID,
        businessType: item.businessType,
      }).then(res => {
        this.$message.success("设置成功");
        this.getTemplateList();
      });
    },
    edit(item) {
      function findIndexInOptions(options, value) {
        for (let i = 0; i < options.length; i++) {
          if (options[i].name === value) {
            return i; // 找到值，返回索引
          }
        }
        return -1; // 值不在数组中，返回 -1
      }

      let setData = () => {
        for (const inputSet of this.dialog.form) {
          for (const inputItem of inputSet) {
            if (inputItem['field'] === 'businessType') {
              inputItem['value'] = findIndexInOptions(inputItem.options, item[inputItem['field']]);
            } else {
              inputItem['value'] = item[inputItem['field']];
            }
          }
        }
      }

      setData();
      this.dialog.chooseItem = item;
      this.buttonName = '立即编辑';
      console.log("dialog: ", this.dialog);
      this.printDialogStatus(true);
    },
    del(item) {
      this.$confirm('您确认要删除吗?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        delTemplate({
          _id: item._id,
        }).then(res => {
          this.page.pageNumber = 1;
          this.$message.success("操作成功");
          this.getTemplateList();
        });
      }).catch(() => {

      });
    },
    cancel() {
      this.editDialog = false;
      this.dialog.form = deepClone(this.dialog.copyForm);
    },
    newAdded() {
      console.log(350);

    },
  }
}
</script>


<style lang="scss" scoped>
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}


.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}

.settement-right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: 100%;
  border-radius: 10px;
  padding-top: 10px;
  margin-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}
</style>
